package network.protocol;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author Erik contains common functions to manipulate a array of
 *         PlayerPackage(players)
 */

@SuppressWarnings("serial")
public class PlayersPackage implements Serializable {
	private static final int ELEMENTS_IN_PLAYERPACKAGE = 6;

	
	/**
	 * convert the giver ArrayList of PlayerPackage to a
	 * correct formated string
	 * @param players
	 * @return
	 */
	public static String toPackage(ArrayList<PlayerPackage> players) {
		StringBuffer buf = new StringBuffer();
		Iterator<PlayerPackage> itr = players.iterator();

		while (itr.hasNext())
			buf.append(itr.next().toPackage());
		return buf.toString();
	}

	/**
	 * convert a correct formated string to a ArrayList of PlayerPackage
	 * format: PlayerPackage + \n + PlayerPackage + .... + \n
	 * @param data
	 * @return
	 */
	public static ArrayList<PlayerPackage> fromPackage(String data) {
		ArrayList<PlayerPackage> res = new ArrayList<PlayerPackage>();

		int end = -1;

		while (data.indexOf('\n') != -1) {
			// cut out the substrings (each part contains 5 \n)
			for (int i = 0; i < ELEMENTS_IN_PLAYERPACKAGE; i++)
				end = data.indexOf('\n', end + 1);
			// convert the substring to playerpackage
			res.add(new PlayerPackage(data.substring(0, end + 1)));
			data = data.substring(end + 1);
			end = 0;
		}
		return res;
	}

	/**
	 * A regular find-function..
	 * @param players
	 * @param ID
	 * @return
	 */
	public static PlayerPackage find(ArrayList<PlayerPackage> players, int ID) {
		Iterator<PlayerPackage> itr = players.iterator();
		while (itr.hasNext()) {
			PlayerPackage p = itr.next();
			if (p.getID() == ID)
				return p;
		}
		return null;
	}

}
